/*
This softtware use BSD licence (http://opensource.org/licenses/BSD-3-Clause)

Copyright (c) 2013, Martin Lebeda
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the Martin Lebeda nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package cz.lebeda.bas;

import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


// TODO Lebeda - repolace marbes.cz to gmail.com

/**
 * @author <a href="mailto:martin.lebeda@gmail.com">Martin Lebeda</a>
 *         Date: 13.11.13
 */
public class RestoreService {

    final Logger logger = LoggerFactory.getLogger(RestoreService.class);

    private String bckIdxName;
    private Repository repository;
    private List<String> pathToRestoreList;
    private final String targetPath;


    /**
     * Create instance of object for restore files from backup.
     *
     * @param bckIdxName indexname for restore source
     * @param repository repository service
     * @param pathToRestoreList path patern for restore
     * @param targetPath target path for restore, if blank, restore to original path
     */
    public RestoreService(String bckIdxName, Repository repository, List<String> pathToRestoreList, String targetPath) {
        this.bckIdxName = bckIdxName;
        this.repository = repository;
        this.pathToRestoreList = pathToRestoreList;
        this.targetPath = targetPath;
    }

    /**
     * execute restore process
     *
     * @throws Exception
     */
    public void run() throws Exception {
        // load index
        Collection<File> bckIdxCollection = FileUtils.listFiles( repository.getMetaPath(),
                new WildcardFileFilter(bckIdxName + "*"),
                TrueFileFilter.INSTANCE);

        // TODO Lebeda - check only one index file

        // find files ro restore
        Set<VOBackupFile> oldFileSet = repository.collectBackupedFilesFromIndex(bckIdxCollection);
        Set<VOBackupFile> restoreFileSet = new HashSet<>();
        for (final String path : pathToRestoreList) {
            //noinspection unchecked
            restoreFileSet.addAll((Collection<VOBackupFile>)
                    CollectionUtils.select(oldFileSet,
                            new Predicate() {
                                @Override
                                public boolean evaluate(Object object) {
                                    VOBackupFile voBackupFile = (VOBackupFile) object;
                                    return StringUtils.startsWithIgnoreCase(voBackupFile.getPath(), path + File.separator);
                                }
                            }));
        }

        // create directory if not exists
        for (String pathForRestore : pathToRestoreList) {
            pathForRestore = changedPathToRestore(pathForRestore, targetPath);
            File baseFile = new File(pathForRestore);
            if (!baseFile.exists()) {
                //noinspection ResultOfMethodCallIgnored
                baseFile.mkdirs(); // TODO Lebeda - ošetřit hodnotu
            }
        }

        // find files in directory
        List<VOBackupFile> newFileList = new ArrayList<>();
        for (String pathForRestore : pathToRestoreList) {
            pathForRestore = changedPathToRestore(pathForRestore, targetPath);
            //noinspection unchecked
            final Collection<File> fileColection = FileUtils.listFiles(new File(pathForRestore),
                    TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);

            for (File file : fileColection) {
                newFileList.add(new VOBackupFile(file));
            }
        }

        // delete files not in index (new or changed)
        //noinspection unchecked
        final Collection<VOBackupFile> toDelete =
                (Collection<VOBackupFile>) CollectionUtils.subtract(newFileList, restoreFileSet);
        for (VOBackupFile voBackupFile : toDelete) {
            FileUtils.forceDelete(new File(voBackupFile.getPath()));
            logger.debug("deleted file: {}", voBackupFile.getPath());
        }

        // restore files not in direcroty
        //noinspection unchecked
        final Collection<VOBackupFile> toRestore =
                (Collection<VOBackupFile>) CollectionUtils.subtract(restoreFileSet, newFileList);

        final Collection<VOBackupFile> toTime = new ArrayList<>();
        for (VOBackupFile voBackupFile : toRestore) {
            String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
            if (voBackupFile.isDirectory()) {
                File dir = new File(path);
                dir.mkdirs(); // TODO Lebeda - zajistit ošetření
                toTime.add(voBackupFile);
            } else if (voBackupFile.getSize() == 0) {
                File file = new File(path);
                file.createNewFile(); // TODO Lebeda - ošetřit
                file.setLastModified(voBackupFile.getModify().getTime());
            } else if (StringUtils.isNotBlank(voBackupFile.getFileHash())) {
                repository.restoreFile(voBackupFile, path);
            } else {
                // TODO Lebeda - chyba
                //                LoggerTools.log("unable to restore ${it}")
            }
        }

        for (VOBackupFile voBackupFile : toTime) {
            String path = changedPathToRestore(voBackupFile.getPath(), targetPath);
            File dir = new File(path);
            dir.setLastModified(voBackupFile.getModify().getTime());
        }

    }

    /**
     * create filename and path for restore.
     *
     * @param pathForRestore original path of backupd file
     * @param targetPath new apth for restore, if blank restore directly to riginal path
     * @return path for restore file
     */
    private String changedPathToRestore(String pathForRestore, String targetPath) {
        String result;
        if (StringUtils.isNotBlank(targetPath)) {
            result = Paths.get(targetPath, pathForRestore.replace(":",File.separator)).toString();
        } else {
            result = pathForRestore;
        }
        return result;
    }
}
